#!/bin/bash
#date=2016/10/11
#单次输入防火墙端口脚本

#获取用户输入并赋值给INPUT
read -p "please input servie port for iptables:" INPUT
#判断用户输入是否满足以下条件，如果不满足就退出程序
if [ ${#INPUT} -gt 5 ] || [ ${#INPUT} -lt 2 ] || [ $INPUT -gt 65535 ] || [ $INPUT -lt 20 ];then
  echo "you input illegal prot"
  exit 1
fi
#判断iptables表里是否存在端口与$INPUT相同，如果相同退出程序
if iptables -L -n|grep -w $INPUT > /dev/null 2>&1;then
  echo "you input port exitst"
  exit 1
else
  case $INPUT in
    22)
	iptables -A INPUT -p tcp --dport $INPUT -j ACCEPT
	iptables -A OUTPUT -p tcp --sport $INPUT -m state --state ESTABLISHED -j ACCEPT
  	iptables -A OUTPUT -p tcp --sport $INPUT -j ACCEPT
	iptables -A INPUT -p tcp --dport $INPUT -m state --state ESTABLISHED -j ACCEPT
    ;;
    53)
	iptables -A INPUT -p tcp --dport $INPUT -j ACCEPT
	iptables -A OUTPUT -p tcp --sport $INPUT -m state --state ESTABLISHED -j ACCEPT
        iptables -A OUTPUT -p tcp --sport $INPUT -j ACCEPT
        iptables -A INPUT -p tcp --dport $INPUT -m state --state ESTABLISHED -j ACCEPT
    ;;
    *)
        iptables -A INPUT -p tcp --dport $INPUT -j ACCEPT
        iptables -A OUTPUT -p tcp --sport $INPUT -m state --state ESTABLISHED -j ACCEPT
    ;;
   esac
   if [ $? -eq 0 ];then
       echo -e "add iptables port \E[32msuccess\E[m"
       read -p "Are you want to save change?" IN
       case $IN in
	 Y|y)
		service iptabels save
	;;
         N|n)
		echo "you no save iptables change,bye...bye...."
		service iptables restart > /dev/null 2>&1
	;;
	*)
		echo "I don't you want to fucn doing,quit...." 
	 	exit 1
       esac
   else
       echo -e "add iptables port \E[31merror\E[m"
       exit 1
   fi
fi
